//
//  LLoginInput.swift
//  LaiLang
//
//  Created by David on 2017/2/5.
//  Copyright © 2017年 David. All rights reserved.
//

import UIKit

enum LLoginInputType{
    case phone
    case password
    case verify
}

class LLoginInput: UIView, UITextFieldDelegate {

    var input: UITextField!
    var type: LLoginInputType = .phone
    
    var maxLength = -1
    
    init(frame: CGRect, type: LLoginInputType) {
        super.init(frame: frame)
        let bgView = UIView(frame: CGRect(x: 0, y: 0, width: frame.width, height: frame.height))
        bgView.layer.borderWidth = 1
        bgView.layer.borderColor = loginThemeColor.cgColor
        bgView.layer.cornerRadius = 4
        addSubview(bgView)
        
        input = UITextField(frame: CGRect(x: 8, y: 0, width: frame.width - 16, height: frame.height))
        input.textColor = loginThemeColor
        input.font = UIFont.boldSystemFont(ofSize: 14)
        input.clearButtonMode = .whileEditing
        input.delegate = self
        
        var phStr = ""
        switch type {
        case .phone:
            let prefix = UILabel(frame: CGRect(x: 8, y: 0, width: 40, height: frame.height))
            prefix.text = "+86"
            prefix.textColor = UIColor.darkGray
            prefix.font = UIFont.boldSystemFont(ofSize: 14)
            bgView.addSubview(prefix)
            input.frame = CGRect(x: 48, y: 0, width: frame.width - 48 - 16, height: frame.height)
            input.keyboardType = .numberPad
            phStr = "请输入您的手机号码"
            break
        case .password:
            phStr = "密码"
            input.isSecureTextEntry = true
            break
        case .verify:
            phStr = "验证码"
            input.keyboardType = .numberPad
            break
        }
        let placeholder = NSMutableAttributedString(string: phStr)
        placeholder.addAttribute(NSForegroundColorAttributeName, value: loginThemeColor, range: NSMakeRange(0, phStr.characters.count))
        input.attributedPlaceholder = placeholder
        bgView.addSubview(input)
        
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if maxLength >= 0{
            
            if textField.text != nil {
                let strLen = textField.text!.characters.count
                if (range.length + range.location > strLen){
                    return false
                }
                let newLength = strLen + string.characters.count - range.length
                return newLength <= maxLength
            }
            
        }
        return true
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

}
